﻿using System.ComponentModel;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using EdlinSoftware.RegexTester.Code;
using System.Diagnostics;

namespace EdlinSoftware.RegexTester.Controls
{
    public class RegexComboBox : ComboBox
    {
        #region Fields

        private const string DefaultStorageFileName = "RegexComboBox.dat";

        private readonly TextLinesStorage _storage = new TextLinesStorage();

        private int _maximumLinesNumber;

        #endregion

        #region Properties

        [Category("Regular expressions")]
        [Description("Name of file to store entered regular expressions between sessions of work.")]
        [DefaultValue(DefaultStorageFileName)]
        public string StorageFileName { get; set; }

        [Category("Behavior")]
        [Description("Maximum number of lines stored in combo box.")]
        [DefaultValue(30)]
        public int MaximumLinesNumber
        {
            [DebuggerStepThrough]
            get { return _maximumLinesNumber; }
            set
            {
                if (_maximumLinesNumber != value)
                {
                    if (value < 1)
                    { value = 1; }

                    _maximumLinesNumber = value;
                    CheckMaximumLinesNumber();
                }
            }
        }

        #endregion

        #region Constructors

        public RegexComboBox()
        {
            StorageFileName = DefaultStorageFileName;
            MaximumLinesNumber = 30;

            AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            AutoCompleteSource = AutoCompleteSource.ListItems;
        }

        #endregion

        #region Methods

        public void LoadStoredExpressions()
        {
            Items.Clear();
            Items.AddRange(_storage.GetLinesFromFile(StorageFileName));
            CheckMaximumLinesNumber();
        }

        public void SaveExpressions()
        {
            _storage.SaveLinesToFile(StorageFileName, Items.OfType<string>());
        }

        public Regex GetRegularExpression(RegexOptions options)
        {
            Regex regex = new Regex(Text, options);

            if (!string.IsNullOrEmpty(Text) && !Items.Contains(Text))
            {
                Items.Insert(0, Text);
                CheckMaximumLinesNumber();
            }

            return regex;
        }

        private void CheckMaximumLinesNumber()
        {
            while (Items.Count > MaximumLinesNumber)
            {
                Items.RemoveAt(Items.Count - 1);
            }
        }

        #endregion
    }
}
